package com.bprogram.service.impl;

import cn.hutool.core.text.StrBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bprogram.controller.CommentFeign;
import com.bprogram.controller.PartionFeign;
import com.bprogram.controller.UserFeign;
import com.bprogram.mapper.VideoMapper;
import com.bprogram.pojo.Partion;
import com.bprogram.pojo.User;
import com.bprogram.pojo.Video;
import com.bprogram.service.VideoService;

import com.bprogram.utils.IdGenerator;
import com.bprogram.utils.RedisUtil;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cai
 * @since 2023-11-21
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {
    @Resource
    private PartionFeign partionFeign;
    @Resource
    private UserFeign userFeign;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private VideoMapper videoMapper;
    @Autowired
    private CommentFeign commentFeign;

    @Override
    public Video saveOrUpdateVideo(Video video) {
        if (StringUtils.isEmpty(video.getVideoId())) {
            IdGenerator idGenerator = new IdGenerator();
            long l = idGenerator.snowflakeId();
            video.setVideoId(l);
            //发布者，时长，分区名称
            getByIds(video, video.getVideoPartitionIds());
            User loginUser = userFeign.getLoginUser();
            video.setUpId(loginUser.getUserId());
            String durationKey = org.apache.commons.lang3.StringUtils.substringAfter(video.getVideoPath(), "/");
            String duration = (String) redisUtil.hget("video", durationKey);
            //设置在redis中这个视频的各个属性初始的默认值
            redisUtil.hset(l + "", "videoPlayTimes", 0);
            redisUtil.hset(l + "", "videoForward", 0);

            redisUtil.hset(l + "", "videoLike", 0);
            redisUtil.hset(l + "", "videoCollects", 0);
            video.setVideoLongth(duration);
             this.save(video);
            return video;
        }
        UpdateWrapper<Video> wrapper = new UpdateWrapper<>();
        Video updateVideo = new Video();
        //更改标题
        if (!StringUtils.isEmpty(video.getVideoTitle())) {
            updateVideo.setVideoTitle(video.getVideoTitle());
        }
        //更改简介
        if (!StringUtils.isEmpty(video.getVideoIntroduct())) {
            updateVideo.setVideoIntroduct(video.getVideoIntroduct());
        }
        //更改分区
        if (!StringUtils.isEmpty(video.getVideoPartitionIds())) {
            updateVideo.setVideoPartitionIds(video.getVideoPartitionIds());
            getByIds(video, video.getVideoPartitionIds());
        }
        //更改是否允许播放
        if (!StringUtils.isEmpty(video.getIsAllow())) {
            updateVideo.setIsAllow(video.getIsAllow());
        }

        if (!StringUtils.isEmpty(video.getVideoLike())) {
            updateVideo.setVideoLike(video.getVideoLike());
        }
        if (!StringUtils.isEmpty(video.getVideoForward())) {
            updateVideo.setVideoForward(video.getVideoForward());
        }
        if (!StringUtils.isEmpty(video.getVideoPlayTimes())) {
            updateVideo.setVideoPlayTimes(video.getVideoPlayTimes());
        }
       wrapper.eq("videoId",video.getVideoId());
        this.update(updateVideo, wrapper);
        return video;
    }

    /**
     * 根据ids查找分区名称
     *
     * @param video
     * @param ids
     * @return
     */
    public Video getByIds(Video video, String ids) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] idsArray = ids.split(",");
        for (int i = 0; i < idsArray.length; i++) {
            Partion partion = partionFeign.getPartion(Long.parseLong(idsArray[i]));
            stringBuilder.append(partion.getPartionName() + "、");
        }
        video.setVideoPartition(stringBuilder.toString());
        return video;
    }

    @Override
    public IPage<Video> getPageVideo(String currentPage, String pageSize, String videoTitle, String location, String partId) {
        IPage<Video> page = new Page<>();
        long ps = Long.parseLong(pageSize);
        long cp = Long.parseLong(currentPage);
        page.setSize(ps);
        page.setCurrent(cp);
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(videoTitle)) {
            wrapper.like("videoTitle", videoTitle);
        }
        if (!StringUtils.isEmpty(location)) {
            if (location.equals("simple")) {
                User loginUser = userFeign.getLoginUser();
                wrapper.eq("upId", loginUser.getUserId());
            } else {
                long upId = Long.parseLong(location);
                wrapper.eq("upId", upId);
            }
        }
        if (!StringUtils.isEmpty(partId)) {
            wrapper.like("videoPartitionIds", partId);
        }
        IPage<Video> videoPage = videoMapper.selectPage(page, wrapper);

        List<Video> list = videoPage.getRecords();
//该视频的评论总数和播放总数
        list.stream().forEach(video->{
            video.setVideoComments(commentFeign.getCounts(video.getVideoId())+"");
            video.setVideoPlayTimes( redisUtil.hget(video.getVideoId() + "", "videoPlayTimes") + "");

        });
        videoPage.setRecords(list);
        return videoPage;

    }

    @Override
    public String getTotalPlayTimesByUpId(long upId) {
        return videoMapper.getTotalPlayTimesByUpId(upId);
    }

    @Override
    public String getTotalLikeByUpId(long upId) {
        return videoMapper.getTotalLikeByUpId(upId);
    }

    @Override
    public String getTotalUploadByUpId(long upId) {
        return videoMapper.getTotalUploadByUpId(upId);
    }

    @Override
    public boolean updateByVideoId(Video video) {
        return videoMapper.updateByVideoId(video);
    }
}
